/*
    duskdawn-map <dd-key.js>
    Copyright (C) 2011  Joshua Redfield

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
*/

//Get DuskDawn map api key
function get_key() {
        var xhr = new XMLHttpRequest();
        var regex = /<input.*?name="key".*?value="([0-9a-f]+)"/ig;
        regex.lastIndex = 0;
        xhr.open("GET", "http://www.die2nite.com/disclaimer?id=14", true);
        xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
                        var matches = regex.exec(xhr.responseText);
                        localStorage["duskdawnkey"] = matches[1];
                }
        }
        xhr.send(null);
}
get_key();

//Request duskdawnkey from localstorage
chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if (request.localstorage == "duskdawnkey")
            sendResponse({duskdawnkey: localStorage.duskdawnkey});
        else
            sendResponse({}); // snub them.
});

//On toolbar icon click -- inject iframe
chrome.browserAction.onClicked.addListener(function(tab) {
        //Get duskdawnkey
        get_key();
        chrome.tabs.executeScript(null, {file: "js/map.js"});
});
